//
//  PublishViewController.m
//  QSBK
//
//  Created by Eric Wang on 4/22/15.
//  Copyright (c) 2015 Eric Wang. All rights reserved.
//
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "PicImageView.h"
#import "Common.h"
#import "PublishViewController.h"
#import "PublishTopBar.h"
#import "InputBar.h"

@interface PublishViewController ()<PublishTioBar,UITextViewDelegate,InputBar,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PicImageView>
@property(nonatomic,copy)NSString *imagePath;
@property(nonatomic,strong)NSString *imageName;
@property(nonatomic,strong)PublishTopBar *topBar;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong)InputBar *inputBar;
@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)PicImageView *picImage;
@end

@implementation PublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addAllSubviews];
    // Do any additional setup after loading the view.
}

- (void)addAllSubviews
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardAppear:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDisappear:) name:UIKeyboardWillHideNotification object:nil];
    
    //bgScrollView
    
    //topBar
    self.view.backgroundColor = [UIColor whiteColor];
    self.topBar = [[PublishTopBar alloc]initWithFrame:CGRectMake(0, StatusBarH, ScreenW, 40)];
    self.topBar.backgroundColor = [UIColor colorWithRed:254/255.0 green:200/255.0 blue:5/255.0 alpha:1.0];
    self.topBar.delegate = self;
    [self.view addSubview:self.topBar];
    
    //bottom bar
    self.inputBar = [[InputBar alloc]initWithFrame:CGRectMake(0, ScreenH-40, ScreenW, 40)];
    self.inputBar.delegate = self;
    self.inputBar.layer.borderWidth = 0.25;
    self.inputBar.layer.borderColor = [UIColor grayColor].CGColor;
    [self.view addSubview:self.inputBar];
    
    
    
    //bgScrollView
    self.bgScrollView = [[UIScrollView alloc]init];
    self.bgScrollView.backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1.0];
    self.bgScrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.bgScrollView];
    NSMutableArray *constraint = [[NSMutableArray alloc]init];
    [constraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[scrollView]-0-|" options:0 metrics:nil views:@{@"scrollView":self.bgScrollView}]];
    [constraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topBar]-0-[scrollView]-0-[inputBar]" options:0 metrics:nil views:@{@"topBar":self.topBar,@"inputBar":self.inputBar,@"scrollView":self.bgScrollView}]];
    [self.view addConstraints:constraint];
   
    self.textView = [[UITextView alloc]init];
    self.textView.frame = CGRectMake(0, 0, ScreenW, 200);
    self.textView.backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1.0];
    self.textView.font = [UIFont systemFontOfSize:15];
    self.textView.text = @"分享你的真实糗事\n你的帖子需要经过多位糗友的审核，笑脸过半就会通过。审核标准位：真实有笑点。上传色情，政治，恐怖内容及泄露隐私者，已经核实将删帖并封号。转载请注明出处。内容版权归糗事百科网站所有。";
    self.textView.delegate = self;
    //self.textView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.bgScrollView addSubview:self.textView];
    
   
    
    
    self.picImage = [[PicImageView alloc]initWithFrame:CGRectMake(10, self.textView.frame.origin.y+self.textView.frame.size.height+20, ScreenW-20, 100)];
    self.picImage.delegate = self;
    self.picImage.hidden = YES;
//    self.picImage.contentMode = UIViewContentModeScaleAspectFill;
   
    [self.bgScrollView addSubview:self.picImage];
}

//topBar delegate

-(void)viewShouldDismiss
{
    [self.textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)publishMessgae
{
    [self postData];
}


//notification keyboard
-(void)keyboardAppear:(NSNotification *)aNotification
{
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:0 animations:^{
        self.inputBar.frame = CGRectMake(0, ScreenH-height-40, ScreenW  , 40);
        
        //[self.view bringSubviewToFront:self.bottomView];
    }];

}
-(void)keyboardDisappear:(NSNotification *)aNotification
{
    [UIView animateWithDuration:0 animations:^{
        self.inputBar.frame = CGRectMake(0, ScreenH-40, ScreenW  , 40);
        
        //[self.view bringSubviewToFront:self.bottomView];
    }];
}



//textview delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.textView.text = @"";
    
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    
}

//inputBar delegate
-(void)picTouched
{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
        
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
    }
}
-(void)cameraTouched
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }

}
-(void)videoTouched
{
    
}

//imagepicker controller


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    
    
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    CGFloat scale = (ScreenW-20)/image.size.width;
    self.picImage.image = image;
    CGFloat height = image.size.height*scale;
    self.picImage.frame = CGRectMake(10, self.textView.frame.size.height+20, ScreenW-20, height);
    
    self.bgScrollView.contentSize = CGSizeMake(ScreenW, self.picImage.frame.origin.y+self.picImage.frame.size.height);
    self.picImage.hidden = NO;
    
    
    [self writeToFile:image];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)writeToFile:(UIImage *)image
{
    NSDate *date = [[NSDate alloc]init];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd:HH:mm:ss"];
    self.imageName = [formatter stringFromDate:date];
    self.imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    self.imagePath = [NSString stringWithFormat:@"%@/%@.png",self.imagePath,self.imageName];
    NSData *data = UIImagePNGRepresentation(image);
    [data writeToFile:self.imagePath atomically:YES];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.textView resignFirstResponder];
}

//imageView delegate
-(void)deleteImage
{
    self.picImage.hidden = YES;
    self.picImage.frame = CGRectMake(10, self.textView.frame.origin.y+self.textView.frame.size.height+20, ScreenW-20, 100);
    self.bgScrollView.contentSize = self.bgScrollView.frame.size;
}


-(void)postData
{
    if(self.picImage.hidden==YES)
    {
        [self publishWithOutImage];
    }else{
        [self publishWithImage];
    }
}

-(void)publishWithOutImage
{
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    NSString *urlString = @"http://localhost:8888/thinkphp_3.2.3/Home/QSBK/publishwithoutimage?";
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    para[@"user_id"]=delegate.user.user_id;
    para[@"content"]=[self.textView.text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation,id responseObject){
        NSLog(@"%@",responseObject);
        NSDictionary *responseObj = (NSDictionary *)responseObject;
        if([[responseObj objectForKey:@"err"] intValue] == 0)
        {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"%@",error);
    }];

}
-(void)publishWithImage
{
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
        NSString *urlString = @"http://localhost:8888/thinkphp_3.2.3/Home/QSBKUPLOAD/upimage?";
    
        NSMutableDictionary *para = [NSMutableDictionary dictionary];
        para[@"user_id"]=delegate.user.user_id;
        para[@"image_width"]=@(self.picImage.image.size.width);
        para[@"image_height"]=@(self.picImage.image.size.height);
        para[@"content"]=[self.textView.text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
        [manager POST:urlString parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        NSData *imageData = [NSData dataWithContentsOfFile:self.imagePath];
        [formData appendPartWithFileData:imageData name:self.imageName fileName:self.imageName mimeType:@"image/png"];
        }success:^(AFHTTPRequestOperation *operation,id responseObject){
        NSLog(@"%@",responseObject);
        }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        NSLog(@"%@",error);
        }];
}
@end
